package com.example.community.controller;

import com.example.community.entity.Event;
import com.example.community.event.EventProducer;
import com.example.community.util.CommunityConstant;
import com.example.community.util.CommunityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: huang
 * @Date: 2021/10/10 16:57
 * @Description:    share 方法是用来生成长图的，并返回一个json字符串，如果成功，则code=0，分享url即是json中"shareUrl"的值。
 */
@Controller
public class ShareController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);

    @Autowired
    private EventProducer eventProducer;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Value("${qiniu.bucket.share.url}")
    private String shareBucketUrl;


    /**
     * 生成长图
     * @param htmlUrl
     * @return
     */
    @RequestMapping(path = "/share", method = RequestMethod.GET)
    @ResponseBody
    public String share(String htmlUrl) {
        //生成一个随机的图片文件名，防止重名
        String fileName = CommunityUtil.generateUUID();

        //异步生成长图，用kafka来处理
        Event event = new Event()
                .setTopic(TOPIC_SHARE)
                .setData("fileName", fileName)
                .setData("htmlUrl", htmlUrl)
                .setData("suffix", ".png");
        eventProducer.fireEvent(event);

        //返回访问路径，把返回路径装入map，用json返回
        Map<String, Object> map = new HashMap<>();
        // [http://localhost:8080/community]/share/image/XXX.png
        //map.put("shareUrl", domain + contextPath + "/share/image/" + fileName );
        map.put("shareUrl", shareBucketUrl + "/" + fileName);

        return CommunityUtil.getJSONString(0, null, map);
    }

    /**
     * 获取图片
     * @param fileName
     * @param response
     */
    //废除
    @RequestMapping(path = "/share/image/{fileName}", method = RequestMethod.GET)
    public void getShareImage(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        if (StringUtils.isBlank(fileName)) {
            throw new IllegalArgumentException("文件名不能为空!");
        }
        //指定返回内容格式
        response.setContentType("image/png");
        //获取存储路径下的文件
        File file = new File(wkImageStorage + "/" + fileName + ".png");


        try {
            //输入流，读取文件
            FileInputStream fileInputStream = new FileInputStream(file);
            //输出流，将文件写入response
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("获取长图失败:" + e.getMessage());
        }

    }

}
